<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="item in scope.row.children" :key="item.id" class="bor-bom">
              <!-- 一级 -->
              <el-col :span="6">
                <el-tag type="primary" closable @close="deleteItemFn(scope.row, item.id)">{{item.authName}}</el-tag>
              </el-col>
              <!-- 二级，三级 -->
              <el-col :span="18">
                <el-row v-for="secItem in item.children" :key="secItem.id" class="bor-bom">
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteItemFn(scope.row, secItem.id)">{{secItem.authName}}</el-tag>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="thrItem in secItem.children" :key="thrItem.id" closable @close="deleteItemFn(scope.row, thrItem.id)">{{thrItem.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 序号 -->
         <el-table-column label="#" type="index"></el-table-column>
         <el-table-column prop="roleName" label="角色名称"></el-table-column>
         <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
         <el-table-column label="操作">
           <template slot-scope="scope">
             <el-button type="primary" icon="el-icon-edit" @click="changeRolesMsgFn(scope.row)">编辑</el-button>
             <el-button type="danger" icon="el-icon-delete" @click="deleteRolesFn(scope.row)">删除</el-button>
             <el-button type="warning" icon="el-icon-setting" @click="editRolesFn(scope.row)">分配权限</el-button>
           </template>
         </el-table-column>
      </el-table>
      <!-- 分配权限 -->
      <el-dialog title="编辑权限" :visible.sync="dialogVisibleRoles" width="50%" @close="closeDialogRoles" ref="rolesRef">
        <span>
          <el-tree :data="treeList" :props="defaultProps" node-key="id" show-checkbox default-expand-all :default-checked-keys="defaultKeys" ref="treeRef"></el-tree>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleRoles = false">取 消</el-button>
          <el-button type="primary" @click="addRolesFn">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色 -->
      <el-dialog title="添加角色" :visible.sync="dialogVisibleRolesBtn" width="50%">
        <span>
          <p> <el-input v-model="addRolesInfo.roleName" placeholder="角色名称"></el-input> </p>
          <p> <el-input v-model="addRolesInfo.roleDesc" placeholder="请输入角色描述"></el-input> </p>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleRolesBtn = false">取 消</el-button>
          <el-button type="primary" @click="addRolesBtn">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色信息 -->
      <el-dialog title="编辑角色" :visible.sync="dialogVisibleRolesChange" width="50%">
        <span>
          <p> <el-input v-model="changeRolesInfo.roleName" placeholder="角色名称"></el-input> </p>
          <p> <el-input v-model="changeRolesInfo.roleDesc" placeholder="请输入角色描述"></el-input> </p>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleRolesChange = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleRolesChangeFn">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      rolesList: [],
      dialogVisibleRoles: false,
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认树形选中的节点
      defaultKeys: [],
      rolesItemId: '',
      dialogVisibleRolesBtn: false,
      addRolesInfo: {
        roleName: '',
        roleDesc: ''
      },
      dialogVisibleRolesChange: false,
      changeRolesInfo: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取权限列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    // 删除一级，二级，三级权限
    deleteItemFn (row, id) {
      this.$confirm('此操作将永久删除权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(row)
        const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        row.children = res.data
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除角色
    deleteRolesFn (row) {
      this.$confirm('此操作将永久删除角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${row.id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getRolesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分配权限
    editRolesFn (row) {
      this.getRolesTree()
      this.getIds(row, this.defaultKeys)
      this.rolesItemId = row.id
      this.dialogVisibleRoles = true
    },
    // 获取树形权限列表
    async getRolesTree () {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.treeList = res.data
    },
    // 递归获取三级权限的id数组
    getIds (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getIds(item, arr)
      })
    },
    // 关闭dialog重置默认的字节点值
    closeDialogRoles () {
      this.defaultKeys = []
    },
    async addRolesFn () {
      let arr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      arr = arr.join(',')
      const { data: res } = await this.$http.post(`roles/${this.rolesItemId}/rights`, { rids: arr })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('修改成功')
      this.dialogVisibleRoles = false
      this.getRolesList()
    },
    // 添加角色按钮
    addRoles () {
      this.dialogVisibleRolesBtn = true
    },
    // 添加角色
    async addRolesBtn () {
      const { data: res } = await this.$http.post('roles', this.addRolesInfo)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.dialogVisibleRolesBtn = false
      this.getRolesList()
    },
    // 编辑
    changeRolesMsgFn (row) {
      this.dialogVisibleRolesChange = true
      this.changeRolesInfo = row
    },
    async dialogVisibleRolesChangeFn () {
      const { data: res } = await this.$http.put(`roles/${this.changeRolesInfo.id}`, this.changeRolesInfo)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.dialogVisibleRolesChange = false
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 8px;
  }
  .bor-bom {
    border-bottom: 1px solid #eee;
  }
  .el-row {
    display: flex;
    align-items: center;
  }
</style>
